<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.model.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.model.content"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.model.status">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="hidden">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.data.faq.add'"
        type="primary"
        @click="confirm"
        >保存</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.data.faq.edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../data.service';
  import { cloneDeep } from 'lodash';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      title: '',
      content: '',
      status: 'normal',
    },
    rules: {
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    },
  });
  const loading = ref(false);
  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.faq.detail(id);
    error === 0 && (form.model = data);
    loading.value = false;
  }
  // 表单关闭时提交
  async function confirm() {
    // 表单验证
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      let submitForm = cloneDeep(form.model);
      const { error } =
        props.modal.params.type == 'add'
          ? await api.faq.add(submitForm)
          : await api.faq.edit(props.modal.params.id, submitForm);
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
    });
  }
  async function init() {
    if (props.modal.params.id) {
      await getDetail(props.modal.params.id);
    }
  }
  onMounted(() => {
    init();
  });
</script>
